package com.sec.etech.sys.msg;

import com.sec.etech.sys.msg.model.EtechEmailMessage;
import lombok.extern.slf4j.Slf4j;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import org.apache.commons.lang3.StringUtils;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.org.api.model.IUser;
import org.openbpm.sys.api.jms.model.msg.NotifyMessage;
import org.openbpm.sys.api.service.PropertyService;
import org.openbpm.sys.api.service.SysIdentityConvert;
import org.openbpm.sys.simplemq.handler.msg.MailHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("etechMailHandler")
public class EtechMailHandler extends MailHandler {

    @Resource
    SysIdentityConvert sysIdentityConvert;

    @Resource
    PropertyService propertyService;

    public String getType() {
        return "email";
    }

    public String getTitle() {
        return "ETech邮件";
    }

    public boolean sendMessage(NotifyMessage notifMessage) {
        EtechEmailMessage mail = new EtechEmailMessage();
        List<? extends IUser> recievers = this.sysIdentityConvert.convert2Users(notifMessage.getReceivers());
        List<String> listTo = new ArrayList<>();
        for(IUser reciver: recievers){
            String email = reciver.getEmail();
            if(StringUtil.isNotEmpty(email)){
                listTo.add(email);
            }
        }
        mail.setTo(StringUtil.join(listTo.toArray(new String[listTo.size()]),","));
        mail.setSubject(notifMessage.getSubject());
        mail.setHtmlContent(notifMessage.getHtmlContent());

        return sendMail(mail);
    }


    //使用微软的ExchangeService API
    //https://github.com/OfficeDev/ews-java-api/wiki/Getting-Started-Guide#maven
    //https://github.com/OfficeDev/ews-java-api

    public boolean sendMail(EtechEmailMessage mail) {

        try {
            if(!enableMail){
                log.warn("邮件未启动，请配置参数etech.email.enabled=true或者设置环境变量enable_mail=true");
            }
            ExchangeService service = getExchangeService();
            EmailMessage msg = new EmailMessage(service);

            boolean isTestMail = true;
            try {
                isTestMail = propertyService.getBooleanByAlias("testMailEnable", true);
                if(isTestMail){
                    log.info("如需关闭邮件发给测试人机制，请设置系统属性  testMailEnable = false");
                }
            }catch (Exception e){
                log.error("获取邮件测试机制属性失败  testMailEnable");
            }


            String subject = mail.getSubject();
            if(StringUtil.isNotEmpty(subjectPrefix)){
                subject = subjectPrefix + subject;
            }
            String content = mail.getHtmlContent();
            String toTip = "";
            //to/cc/bcc
            if (StringUtils.isNotEmpty(mail.getTo())) {
                if(isTestMail){
                    toTip += " TO:"+ mail.getTo();
                }else {
                    String[] tos = mail.getTo().split(",");
                    for (String to : tos) {
                        if(StringUtil.isNotEmpty(to) && to.indexOf("@")>0){
                            msg.getToRecipients().add(to);
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(mail.getCc())) {
                if(isTestMail){
                    toTip += " CC:"+ mail.getCc();
                }else {
                    String[] ccs = mail.getCc().split(",");
                    for (String cc : ccs) {
                        if(StringUtil.isNotEmpty(cc) && cc.indexOf("@")>0){
                            msg.getCcRecipients().add(cc);
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(mail.getBcc())) {
                if(isTestMail){
                    toTip += " BCC:"+ mail.getBcc();
                }else {
                    String[] bccs = mail.getBcc().split(",");
                    for (String bcc : bccs) {
                        if(StringUtil.isNotEmpty(bcc) && bcc.indexOf("@")>0){
                            msg.getBccRecipients().add(bcc);
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(mail.getFiles())) {
                String[] files = mail.getFiles().split(",");
                for (String file : files) {
                    msg.getAttachments().addFileAttachment(file);
                }
            }
            if(isTestMail){
                String testMailToProp = propertyService.getByAlias("testMailTo");
                String testMailToAll = testMailTo;
                if(StringUtil.isNotEmpty(testMailToProp)){
                    testMailToAll = testMailTo + "," + testMailToProp;
                }
                String[] testTo = testMailToAll.split(",");
                for(String to: testTo){
                    if(StringUtil.isNotEmpty(to)){
                        msg.getToRecipients().add(to);
                    }
                }
                subject = "T:"+subject;
                content = content + "\r\n这是Java Etech测试邮件，实际收件人信息："+ "\r\n" + toTip;
            }
            if(isTestMail){
                String to = mail.getTo();
                String cc = mail.getCc();
                String bcc = mail.getBcc();

                String myEmailAdress = "fanyq@shanghai-electric.com";
                if (myEmailAdress.equals(to) || myEmailAdress.equals(cc) || myEmailAdress.equals(bcc) ){
                    msg.getToRecipients().clear();
                    msg.getCcRecipients().clear();
                    msg.getBccRecipients().clear();
                    msg.getBccRecipients().add("fanyq@shanghai-electric.com");
                }
            }
            msg.setSubject(subject);

            if(content.indexOf("<html xmlns='http://www.w3.org/1999/xhtml'>")>0){
                // 已添加
            }else {
                //  添加邮件尾
                String mailTail = "&nbsp&nbsp注意：此邮件为平台自动发送，请勿回复！";
                if(content.indexOf("此邮件为平台自动发送，请勿回复")==-1){
                    content += mailTail;
                }
                content = createHtmlContext(subject, content);
            }
            msg.setBody(MessageBody.getMessageBodyFromText(content));

            if(enableMail){
                msg.send(); //发送
            }

            log.debug(String.format("mail send: to=\r\n%S\r\n, subject=\r\n%S\r\n, content=\r\n%S\r\n", msg.getToRecipients(), msg.getSubject(), msg.getBody().toString()));
        } catch (Exception e) {
            // TODO 重发尝试
            log.error("send mail error:"+e.getMessage());
        }
        return true;
    }
    private String createHtmlContext(String subject, String textContext){
        String bodyStr = "<!DOCTYPE html PUBLIC ' -//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
        bodyStr += "<html xmlns='http://www.w3.org/1999/xhtml'>";
        bodyStr += "<head>";
        bodyStr += "<title>" + subject.replace(" ", "") + " | ETech以太客-技术工作平台</title>";
        bodyStr += "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";
        bodyStr += "</head>";
        bodyStr += "<body>";
        bodyStr += textContext;
        bodyStr += "</body>";
        bodyStr += "</html> ";
        return  bodyStr;
    }

    private ExchangeService getExchangeService() {
        if(exchangeService==null){
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
            ExchangeCredentials credentials = new WebCredentials(emailAccount, emailPwd, emailDomain);
            service.setCredentials(credentials);
            try {
                service.setUrl(new URI(emailServiceUrl));
                // 邮件超时时间默认5秒
                service.setTimeout(5000);  //default
                exchangeService = service;
            } catch (URISyntaxException e) {
                log.error("getExchangeService error", e);
            }
        }
        return exchangeService;
    }
    private static ExchangeService exchangeService = null;

    @Value("${etech.email.enabled:true}")
    private Boolean enableMail;
    //@Value("${etech.email.is-test:true}")
    //private boolean isTestMail = true;
    @Value("${etech.email.test-to:}")
    private String testMailTo;

    @Value("${etech.subject-prefix:以太客-}")
    private String subjectPrefix;

    @Value("${etech.email.account:stc_itservice}")
    private String emailAccount;
    @Value("${etech.email.domain:AD01}")
    private String emailDomain;
    @Value("${etech.email.address:stc_itservice@shanghai-electric.com}")
    private String emailAddress;
    @Value("${etech.email.pwd:dp@012}")
    private String emailPwd;
    @Value("${etech.email.service-url:https://webmail.shanghai-electric.com/EWS/Exchange.asmx}")
    private String emailServiceUrl;

    public static void main(String[] args) {

        try{
            EtechMailHandler mailHandler = new EtechMailHandler();
            EtechEmailMessage mail = new EtechEmailMessage();

            // to/cc/bcc
            mail.setTo("stc_itservice@shanghai-electric.com");
            mail.setSubject("this is a test mail");
            mail.setHtmlContent("please delete it, this a test mail only.");

            mailHandler.sendMail(mail);

        }catch (Exception e){

        }


    }

}
